import os
import logging

BASEDIR = os.path.abspath(os.path.dirname(__name__))


class InfoFilter(logging.Filter):
    def filter(self, record):
        """
        只筛选级别为info的log
        :param record:
        :return:
        """
        if logging.INFO <= record.levelno < logging.ERROR:
            # 已经是INFO级别了，利用父类，返回1
            return super().filter(record)
        else:
            return 0


class Config(object):
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    SECRET_KEY = "you can not guess this stings"

    # 日志配置
    LOG_PATH = os.path.join(BASEDIR, "logs")
    LOG_PATH_ERROR = os.path.join(LOG_PATH, "error.log")
    LOG_PATH_INFO = os.path.join(LOG_PATH, "info.log")
    # if not os.path.exists(LOG_PATH_INFO):
    #     os.mkdir(LOG_PATH_INFO)
    # if not os.path.exists(LOG_PATH_ERROR):
    #     os.mkdir(LOG_PATH_ERROR)

    LOG_FILE_MAX_BYTES = 20 * 1024 * 1024   # 20M
    LOG_FILE_BACK_COUNT = 5                 # 日志文件备份数目

    @classmethod
    def init_app(cls, app):
        # 可添加loggin setting模板
        from logging.handlers import RotatingFileHandler
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(process)d %(thread)d %(funcName)s %(pathname)s %(lineno)s %(message)s')

        file_handler_info = RotatingFileHandler(filename=cls.LOG_PATH_INFO)
        file_handler_info.setFormatter(formatter)
        file_handler_info.setLevel(logging.INFO)
        info_filter = InfoFilter()
        file_handler_info.addFilter(info_filter)
        app.logger.addHandler(file_handler_info)

        file_handler_error = RotatingFileHandler(filename=cls.LOG_PATH_ERROR)
        file_handler_error.setFormatter(formatter)
        file_handler_error.setLevel(logging.ERROR)
        app.logger.addHandler(file_handler_error)


class DevelopmentConfig(Config):
    DEBUG = True
    # 追踪数据库的修改，如果不设置会警告，但并不影响代码执行
    SQLALCHEMY_TRACK_MODIFICATIONS = True
    PRESERVE_CONTEXT_ON_EXCEPTION = False
    # 开启显示sql语句
    # SQLALCHEMY_ECHO = True
    SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:mysql#57@127.0.0.1:3306/tech_duty?charset=utf8"


class TestConfig(Config):
    DEBUG = True
    # 开启慢查询记录，
    SQLALCHEMY_RECORD_QUERIES = True
    # 慢查询阈值为0.5s
    FLASKY_DB_QUERY_TIMEOUT = 0.5
    SQLALCHEMY_TRACK_MODIFICATIONS = True
    PRESERVE_CONTEXT_ON_EXCEPTION = False
    SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:mysql@127.0.0.1:3306/tech_duty?charset=utf8"


class ProductConfig(Config):
    DEBUG = False
    SQLALCHEMY_TRACK_MODIFICATIONS = True
    PRESERVE_CONTEXT_ON_EXCEPTION = False
    SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:*@127.0.0.1:3306/tech_duty?charset=utf8"


baseConfig = {
    'development': DevelopmentConfig,
    'product': ProductConfig,
    'test': TestConfig,
    'default': DevelopmentConfig
}
